<?php

/**
 * SocialEnginePro
 *
 * @category   Application_Extensions
 * @package    tv
 * @author     Azim
 */

/**
 * @category   Application_Extensions
 * @package    tv
 */
class Tv_TvController extends Core_Controller_Action_Standard {

    public function init() {
        if (!$this->_helper->requireAuth()->setAuthParams('tv', null, 'view')->isValid())
            return;

        if (0 !== ($item_id = (int) $this->_getParam('tv_id')) &&
                null !== ($item = Engine_Api::_()->getItem('tv', $item_id))) {
            Engine_Api::_()->core()->setSubject($item);
        }
    }

    public function editAction() {
        if (!$this->_helper->requireUser()->isValid())
            return;
        if (!$this->_helper->requireSubject('tv')->isValid())
            return;
        if (!$this->_helper->requireAuth()->setAuthParams(null, null, 'edit')->isValid())
            return;

        // Get navigation
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('tv_main');
        $this->view->tv = $tv = Engine_Api::_()->core()->getSubject();

        $this->view->form = $form = new Tv_Form_Edit();

        $form->populate($tv->toArray());

        $auth = Engine_Api::_()->authorization()->context;
        $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
        foreach ($roles as $role) {
            if (1 === $auth->isAllowed($tv, $role, 'view') && isset($form->auth_view)) {
                $form->auth_view->setValue($role);
            }
            if (1 === $auth->isAllowed($tv, $role, 'comment') && isset($form->auth_comment)) {
                $form->auth_comment->setValue($role);
            }
        }

        if (!$this->getRequest()->isPost() || !$form->isValid($this->getRequest()->getPost())) {
            return;
        }

        $table = $tv->getTable();

        $db = $table->getAdapter();
        $db->beginTransaction();

        try {

            $values = $form->getValues();

            $tv->setFromArray($values);
            $tv->save();



            // CREATE AUTH STUFF HERE
            $auth = Engine_Api::_()->authorization()->context;
            $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');

            if (empty($values['auth_view'])) {
                $values['auth_view'] = 'everyone';
            }

            if (empty($values['auth_comment'])) {
                $values['auth_comment'] = 'everyone';
            }

            if (empty($values['favourite'])) {
                $values['favourite'] = 'everyone';
            }
            if (empty($values['invate'])) {
                $values['invate'] = 'everyone';
            }


            $viewMax = array_search($values['auth_view'], $roles);
            $commentMax = array_search($values['auth_comment'], $roles);
            $favouriteMax = array_search($values['favourite'], $roles);
            $inviteMax = array_search($values['invate'], $roles);



            foreach ($roles as $i => $role) {
                $auth->setAllowed($tv, $role, 'view', ($i <= $viewMax));
                $auth->setAllowed($tv, $role, 'comment', ($i <= $commentMax));
                $auth->setAllowed($tv, $role, 'favourite', ($i <= $favouriteMax));
                $auth->setAllowed($tv, $role, 'invite', ($i <= $inviteMax));
            }

            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }

        return $this->_forward('success', 'utility', 'core', array(
                    'messages' => array(Zend_Registry::get('Zend_Translate')->_('TV was edit successfully')),
                    'redirect' => $this->_helper->redirector->gotoRoute(array('tv_id' => $tv->getIdentity()), 'tv_specific', true),
                ));
    }

    public function viewAction() {
        if (!$this->_helper->requireSubject('tv')->isValid())
            return;

        $this->view->tv = $tv = Engine_Api::_()->core()->getSubject();
        $viewer = Engine_Api::_()->user()->getViewer();



        $money = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('money');

        if ($money) {
            if ($tv->state == 1) {
                $paid = Engine_Api::_()->getDbtable('orders', 'money')->getItemPaid($tv);
                if (!$paid) {
                    $this->_helper->redirector->gotoRoute(array('action' => 'paid', 'id' => $tv->getIdentity(), 'type' => $tv->getType()), 'money_order');
                }
            }
        }






        if (!$this->_helper->requireAuth()->setAuthParams($tv, null, 'view')->isValid())
            return;


        if ($tv->status == 1) {
            if (!$tv->isOwner($viewer)) {
                $tv->view_count++;
                $tv->save();
            }
            $this->view->videoEmbedded = $embedded = $tv->getContent(true);
        }

        // Render
        $this->_helper->content
                //->setNoRender()
                ->setEnabled()
        ;
    }

    public function deleteAction() {
        $viewer = Engine_Api::_()->user()->getViewer();
        $tv = Engine_Api::_()->core()->getSubject();
        if (!$this->_helper->requireAuth()->setAuthParams($tv, null, 'delete')->isValid())
            return;

        // In smoothbox
        $this->_helper->layout->setLayout('default-simple');

        $this->view->form = $form = new Tv_Form_Delete();

        if (!$tv) {
            $this->view->status = false;
            $this->view->error = Zend_Registry::get('Zend_Translate')->_("TV doesn't exists or not authorized to delete");
            return;
        }

        if (!$this->getRequest()->isPost()) {
            $this->view->status = false;
            $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid request method');
            return;
        }

        $db = $tv->getTable()->getAdapter();
        $db->beginTransaction();

        try {
            $tv->delete();
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }

        $this->view->status = true;
        $this->view->message = Zend_Registry::get('Zend_Translate')->_('Tv has been deleted.');
        return $this->_forward('success', 'utility', 'core', array(
                    'parentRedirect' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action' => 'browse'), 'tv_general', true),
                    'messages' => Array($this->view->message)
                ));
    }

    public function inviteAction() {
        if (!$this->_helper->requireUser()->isValid())
            return;
        if (!$this->_helper->requireSubject('tv')->isValid())
            return;



        $viewer = Engine_Api::_()->user()->getViewer();
        $this->view->tv = $tv = Engine_Api::_()->core()->getSubject();
        $this->view->friends = $friends = $viewer->membership()->getMembers();

        // Prepare form
        $this->view->form = $form = new Tv_Form_Invite();

        $count = 0;
        foreach ($friends as $friend) {

            $form->users->addMultiOption($friend->getIdentity(), $friend->getTitle());
            $count++;
        }
        $this->view->count = $count;

        // throw notice if count = 0
        if ($count == 0) {
            return $this->_forward('success', 'utility', 'core', array(
                        'messages' => array(Zend_Registry::get('Zend_Translate')->_('You have no friends you can invite.')),
                        'layout' => 'default-simple',
                        'parentRefresh' => true,
                    ));
        }

        // Not posting
        if (!$this->getRequest()->isPost()) {
            return;
        }

        if (!$form->isValid($this->getRequest()->getPost())) {
            return;
        }


        // Process
        $table = $tv->getTable();
        $db = $table->getAdapter();
        $db->beginTransaction();

        try {
            $usersIds = $form->getValue('users');

            $notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
            foreach ($friends as $friend) {
                if (!in_array($friend->getIdentity(), $usersIds)) {
                    continue;
                }


                $notifyApi->addNotification($friend, $viewer, $tv, 'tv_invite');
            }


            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }

        return $this->_forward('success', 'utility', 'core', array(
                    'messages' => array(Zend_Registry::get('Zend_Translate')->_('Members invited')),
                    'layout' => 'default-simple',
                    'parentRefresh' => true,
                ));
    }

    public function favouriteAction() {

        $viewer = Engine_Api::_()->user()->getViewer();
        $tv = Engine_Api::_()->core()->getSubject();
//        if (!$this->_helper->requireAuth()->setAuthParams($tv, null, 'favourite')->isValid())
//            return;
        // In smoothbox
        $this->_helper->layout->setLayout('default-simple');

        $this->view->form = $form = new Tv_Form_Favourite();

        if (!$tv) {
            $this->view->status = false;
            $this->view->error = Zend_Registry::get('Zend_Translate')->_("TV doesn't exists or not authorized to favourite");
            return;
        }

        if (!$this->getRequest()->isPost()) {
            $this->view->status = false;
            $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid request method');
            return;
        }
        $values = array();
        $values['user_id'] = $viewer->getIdentity();
        $values['tv_id'] = $tv->getIdentity();
        $table = Engine_Api::_()->getDbtable('favourites', 'tv');
        $db = $table->getAdapter();
        $db->beginTransaction();
        try {
            $row = $table->createRow();
            $row->setFromArray($values);
            $row->save();
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }

        $this->view->status = true;
        $this->view->message = Zend_Registry::get('Zend_Translate')->_('Tv has been favourite.');
        return $this->_forward('success', 'utility', 'core', array(
                    'parentRefresh' => true,
                    'messages' => Array($this->view->message)
                ));
    }

    public function unsetfavouriteAction() {

        $viewer = Engine_Api::_()->user()->getViewer();
        $tv = Engine_Api::_()->core()->getSubject();
//        if (!$this->_helper->requireAuth()->setAuthParams($tv, null, 'favourite')->isValid())
//            return;
        // In smoothbox
        $this->_helper->layout->setLayout('default-simple');

        $this->view->form = $form = new Tv_Form_Unsetfavourite();

        if (!$tv) {
            $this->view->status = false;
            $this->view->error = Zend_Registry::get('Zend_Translate')->_("TV doesn't exists or not authorized to favourite");
            return;
        }

        if (!$this->getRequest()->isPost()) {
            $this->view->status = false;
            $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid request method');
            return;
        }



        $table = Engine_Api::_()->getDbtable('favourites', 'tv');
        $db = $table->getAdapter();
        $db->beginTransaction();
        try {
            $row = $table->fetchRow($table->select()->where('user_id =?', $viewer->getIdentity())->where('tv_id =?', $tv->getIdentity()));

            $row->delete();
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }

        $this->view->status = true;
        $this->view->message = Zend_Registry::get('Zend_Translate')->_('Tv has been unset favourite.');
        return $this->_forward('success', 'utility', 'core', array(
                    'parentRefresh' => true,
                    'messages' => Array($this->view->message)
                ));
    }

    public function unsetfeaturedAction() {
        $viewer = Engine_Api::_()->user()->getViewer();
        $tv = Engine_Api::_()->core()->getSubject();

        $this->_helper->layout->setLayout('default-simple');

        $this->view->form = $form = new Tv_Form_Unsetfeatured();

        if (!$tv) {
            $this->view->status = false;
            $this->view->error = Zend_Registry::get('Zend_Translate')->_("TV doesn't exists or not authorized to featured");
            return;
        }

        if (!$this->getRequest()->isPost()) {
            $this->view->status = false;
            $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid request method');
            return;
        }

        $table = $tv->getTable();
        $db = $table->getAdapter();
        $db->beginTransaction();
        try {
            $tv->featured = 0;

            $tv->save();
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }

        $this->view->status = true;
        $this->view->message = Zend_Registry::get('Zend_Translate')->_('TV has been unset featured.');
        return $this->_forward('success', 'utility', 'core', array(
                    'parentRefresh' => true,
                    'messages' => Array($this->view->message)
                ));
    }

    public function featuredAction() {

        $viewer = Engine_Api::_()->user()->getViewer();
        $tv = Engine_Api::_()->core()->getSubject();
        if (!$this->_helper->requireAuth()->setAuthParams($tv, null, 'featured')->isValid())
            return;
        // In smoothbox
        $this->_helper->layout->setLayout('default-simple');

        $this->view->form = $form = new Tv_Form_Featured();

        if (!$tv) {
            $this->view->status = false;
            $this->view->error = Zend_Registry::get('Zend_Translate')->_("TV doesn't exists or not authorized to featured");
            return;
        }

        if (!$this->getRequest()->isPost()) {
            $this->view->status = false;
            $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid request method');
            return;
        }

        $table = $tv->getTable();
        $db = $table->getAdapter();
        $db->beginTransaction();
        try {
            $tv->featured = 1;

            $tv->save();
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }

        $this->view->status = true;
        $this->view->message = Zend_Registry::get('Zend_Translate')->_('TV has been featured.');
        return $this->_forward('success', 'utility', 'core', array(
                    'parentRefresh' => true,
                    'messages' => Array($this->view->message)
                ));
    }

}